#!/usr/bin/python
#coding=utf-8

import Cookie
import datetime
import calendar
import email
from igor import logging

class Response:
    
    def __init__(self, start_response, status = '200 OK', content_type='text/html;charset=utf-8'):
        self.status = status
        self.content_type = content_type
        self.start_response = start_response
        self.body = []
        self.response_headers = []
        
    def set_header(self, header):
        self.response_headers.append(header)  
        
    def respond(self, body=None):
        self.response_headers.append(('Content-type', self.content_type))  
        if body:
            self.body.append(body)
        body_len = sum(len(line) for line in self.body)
        self.response_headers.append(('Content-Length', str(body_len)))  
        self.start_response(self.status, self.response_headers)  
        return self.body

    def set_cookie(self, name, value, domain=None, expires=None, path='/',
                   expires_days=None, max_age=None, http_only=True):
        if not hasattr(self, 'cookie'):
            self.cookie = Cookie.SimpleCookie()
        self.cookie[name] = value
        morsel = self.cookie[name]
        if domain:
            morsel['domain'] = domain
        if expires_days is not None and not expires:
            expires = datetime.datetime.utcnow() + datetime.timedelta(
                days=expires_days)
        if expires:
            timestamp = calendar.timegm(expires.utctimetuple())
            morsel["expires"] = email.Utils.formatdate(timestamp, localtime=False, usegmt=True)
        if path:
            morsel['path'] = path
        if max_age:
            morsel['max-age'] = max_age 
        cookie_str = self.cookie.output()
        parts = cookie_str.split(':')
        cookie_title, cookie_content = (parts[0], ' '.join(str for str in parts[1:]))
        if http_only:
            cookie_content += ';HttpOnly'
        logging.log('cookie-content:' + str(cookie_content))
        self.set_header((cookie_title, cookie_content))

    def clear_cookie(self, name, value='', path='/', domain=None):
        expires = datetime.datetime.utcnow() - datetime.timedelta(100)
        self.set_cookie(name, value, domain=domain, expires=expires, path=path)

    def redirect(self, url):
        self.response_headers.append(('Location', url))
        self.start_response('302 OK', self.response_headers)
        return self.body 

    
